package com.wennn.top.security.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wennn.top.security.exception.UserstatusException;
import com.wennn.top.security.model.SessionUser;
import com.wennn.top.security.vo.AuthUser;
import com.wennn.top.shop.biz.user.entity.YxUser;
import com.wennn.top.shop.biz.user.es.UserStatus;
import com.wennn.top.shop.biz.user.service.IYxUserService;
import com.wennn.top.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Objects;

/**
 * 获取db中的用户
 * @author: wennn
 * @date: 7/10/20 2:58 PM
 */
@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    IYxUserService iYxUserService;


    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        YxUser one = iYxUserService.getOne(Wrappers.lambdaQuery(YxUser.class).eq(YxUser::getUsername,name));
        if (Objects.isNull(one)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        if (UserStatus.freeze.getCode() == one.getStatus()) {
            throw new UserstatusException("用户被冻结");
        }

        SessionUser sessionUser = SessionUser.builder();
        BeanUtils.copyProperties(one, sessionUser);
        sessionUser.setId(one.getUid());
        sessionUser.set("status",one.getStatus());
        AuthUser user = new AuthUser(sessionUser, one.getPassword(), Collections.emptyList());
        return user;
    }

    /**
     * 保存登陆状态日志
     */
    public void saveLoginAction(AuthUser authUser, boolean isSuccess) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //  这里要转为异步 或消息才行
            log.debug("这里是记录登陆日志,登陆人:{},登陆状态:{}", authUser, isSuccess);

            YxUser yxUser = new YxUser();
            yxUser.setLastTime(DateUtil.nowIntTime());
            yxUser.setLastIp(request.getRemoteHost());
 ;
            if (isSuccess) {
            } else {

            }
            iYxUserService.update(yxUser, Wrappers.lambdaQuery(YxUser.class)
                    .eq(YxUser::getUid, authUser.getSessionUser().getId()));
        } catch (Exception e) {
            log.error("报错用户登陆日志失败",e);
        }


    }
}
